package com.wtgroup.demo.leetcode.q008;

/**
 * 简单遍历检索方式
 *
 * @author dafei
 * @version 0.1
 * @date 2021/3/25 14:22
 */
public class S_WhileIterate {

    public static void main(String[] args) {
        S_WhileIterate exe = new S_WhileIterate();
        String[] ss = {
                // "42",
                // "   -42",
                // "words and 987",
                // "4193 with words",
                // "-91283472332",
                "2147483648"
        };
        for (String s : ss) {
            System.out.println(exe.myAtoi(s));
        }
    }


    /**
     * 简单遍历, 代码简洁精巧.
     * @param s
     * @return
     */
    public int myAtoi(String s) {
        if (s == null || s.length()==0) {
            return 0;
        }
        char[] chars = s.toCharArray();
        int i = 0;
        // 略过空格
        while (chars[i] == ' ') {
            i++;
            // 全是空格, return 0
            if (i>=chars.length) {
                return 0;
            }
        }
        // 空格消耗掉后, 仅允许符号位或数字, 其他, 退出.
        char maysign = chars[i];
        int signFlag = 1;
        if (maysign == '+' || maysign == '-') {
            if(maysign == '-') signFlag = -1;
            i++;
        }

        int ans = 0;
        char next = 0;
        while (i<chars.length && isDigit(next = chars[i++])) {
            int pop = next - '0';
            // 判断溢出. 本题因为溢出就截断取临界值, 只用判断正数情况, 正数情况溢出, 负数要么溢出要么刚好等于临界值. (正7负8)
            if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7)) {
                return signFlag > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            ans = ans * 10 + pop;
        }

        return signFlag * ans;
    }

    private boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }
}
